package com.seata.demo.order.service.impl;

import com.seata.demo.order.entity.Order;
import com.seata.demo.order.feign.AccountFeignClient;
import com.seata.demo.order.feign.StorageFeignClient;
import com.seata.demo.order.mapper.OrderMapper;
import com.seata.demo.order.service.SagaOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class SagaOrderServiceImpl implements SagaOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StorageFeignClient storageFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Override
    public void startSagaTransaction(String userId, String commodityCode, Integer count, BigDecimal money) {
        // 方法体可以为空，Saga状态机会控制整个流程
//        // 1. 创建订单
//        Order order = new Order();
//        order.setUserId(userId);
//        order.setCommodityCode(commodityCode);
//        order.setCount(count);
//        BigDecimal price = new BigDecimal(100); // 假设单价100元
//        order.setMoney(price.multiply(new BigDecimal(count)));
//        order.setStatus(0); // 0-创建中
//        orderMapper.insert(order);
    }

    @Override
    public void createOrder(String userId, String commodityCode, Integer count, BigDecimal money) {
        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(count);
        order.setMoney(money);
        order.setStatus(1); // 直接设置为已完成
        orderMapper.insert(order);
    }

    @Override
    public void cancelOrder(String userId, String commodityCode, Integer count, BigDecimal money) {
        // 查询该用户最近的订单并取消
        // 实际应用中应该根据业务场景实现具体的取消逻辑
        Order order = new Order();
        // 这里简化处理，实际应查询后更新
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setStatus(2); // 已取消
        orderMapper.updateStatus(order.getId(), 2);
    }
}
